import { watch, ref, isRef, computed, watchEffect } from "vue";
import { asyncComputed, refDebounced } from "@vueuse/core";
import { getShijiItemByidsLazyFields, requestByidsLazyFields } from "@/api/cloudbase-sgbedit";
import { $toast } from "@/utils/utils";
let audio;

function getAudio() {
  if (!audio) {
    audio = new Audio();
  }
  return audio;
}

async function play() {
  if (audio) {
    audio.play();
  }
}

function pause() {
  if (audio) {
    audio.pause();
  }
}

function togglePause() {
  if (audio) {
    if (audio.paused) {
      play();
    } else {
      pause();
    }
  }
}

function setSrc(src) {
  getAudio().src = src;
}

async function getAdUrl(id) {
  try {
    const res = await requestByidsLazyFields([id], ["adUrl"]);
    console.log("res-->", res);
    let adUrl = "";
    if (Array.isArray(res?.data) && res?.data.length > 0) {
      adUrl = res?.data[0].adUrl;
    }
    return adUrl;
  } catch (error) {
    return "";
  }
}

export default function usePlayer(modelValue, onChange) {
  let adUrl = "";
  let id;
  let loading = refDebounced(false, 20000);
  console.log("modelValue-->", modelValue.value?.payload);

  function initEvent() {
    getAudio().onended = () => {
      console.log("音频播放结束");
      modelValue.value.isPlayAudio = false;
      onChange();
    };

    getAudio().onplay = () => {
      console.log("音频开始播放");
      modelValue.value.isPlayAudio = true;
      onChange();
    };

    getAudio().onpause = () => {
      modelValue.value.isPlayAudio = false;
      onChange();
    };

    getAudio().onloadstart = () => {
      console.log("开始加载音频");
      loading.value = true;
    };

    getAudio().oncanplaythrough = () => {
      console.log("可以流畅的播放到底");
      loading.value = false;
    };
    getAudio().onerror = () => {
      console.log("音频加载错误");
      loading.value = false;
      $toast.error("音频加载错误");
    };
  }
  async function togglePlay(played) {
    const mv = isRef(modelValue) ? modelValue.value : modelValue;

    const newId = mv?.payload?.value;

    if (newId !== id) {
      adUrl = await getAdUrl(newId);
    }
    if (adUrl) {
      if (newId !== id) {
        setSrc(adUrl);
        initEvent();
        id = newId;
      }
      togglePause();
    }
  }

  watchEffect(() => {
    modelValue.value?.payload;
    pause();
  });

  return {
    togglePlay,
    loading,
  };
}
